<?php
/**
 *  记录日志的公用方法: 将用户的非读操作sql存储到数据库
 *  @author chamlinsun@qq.com on 20171207
 */
class logs {
    
    /**
     * @abstract 添加预约单日志
     * @param int $purchaseorder_id 预约单号
     * @param string $info 消息
     * @param int $result 操作结果 0失败、1成功[默认1]
     */
    public static function purchaseorder_log($purchaseorder_id, $info, $result = 1) {
        $action = 'purchaseorders';
        return self::write_log($purchaseorder_id, $action, $result, '', $info);
    }

    /**
     * 1.自动获取相关的非读操作数据（操作人，操作sql，操作时间等）
     * 2.将获取的数据存入op_logs
     */
    public static function write_log($data_id = '0', $action = '', $result = 1, $data = '', $resultInfo = ''){
        if(!$data_id) {
            $data_id = 0;
        }
        if(!is_array($data_id)) {
            $data_id = explode(',', $data_id);
        }
        $id_arr = array_map('intval', $data_id);
        if(!$action) {
            $action = addslashes(str_replace('/index.php/','',$_SERVER['PHP_SELF']));
        } else {
            $action = addslashes($action);
        }
        if(empty($data)) {
            //$data = DB::$query_sql;
            $data = Kohana_Database_Query::$query_sql;
            unset($data[1]);
        }
        if(!empty($data)){
            $data = addslashes(json_encode($data));
            $url = addslashes(self::get_current_url());
            $user = User::active_user();
            $username = addslashes($user->name);
            $result = $result ? 1 : 0;
            $values = array();
            $resultInfo = addslashes($resultInfo);
            foreach($id_arr as $key=> $id) {
                $values[] = "('{$action}', '{$url}', '{$id}', '{$data}', {$result}, '{$resultInfo}', '{$username}')";
            }
            $sql = "INSERT INTO `op_logs` (action, url, data_id, `data`, result, result_info, username) VALUES " . implode(',', $values);
            DB::query(Database::INSERT,$sql)->execute('newerp');
            unset($data);
        }
    }
    //获取当前操作的url
    private static function get_current_url() {
        $current_url = 'http://';
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
            $current_url = 'https://';
        }
        if ($_SERVER['SERVER_PORT'] != '80') {
            $current_url .= $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
        } else {
            $current_url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        }
        return $current_url;
    }
}
